<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.chooseABrand')"
    :close-on-click-modal="false"
    top="5vh"
    :append-to-body="true"
    class="component-brand-select"
  >
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item :label="$t('product.brandName')+':'">
            <el-input
              v-model.trim="brandName"
              clearable
              :placeholder="$t('product.brandName')"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch"
            >
              {{ $t("order.query") }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div class="brand-select-table table-con">
        <el-table
          ref="brandTableRef"
          v-loading="dataListLoading"
          :data="dataList"
          header-cell-class-name="table-header"
          style="width: 100%"
          @selection-change="selectChangeHandle"
        >
          <el-table-column
            v-if="isSingle"
            width="50"
            header-align="center"
            align="center"
          >
            <template #default="scope">
              <div>
                <el-radio
                  v-model="singleSelectBrandId"
                  :label="scope.row.brandId"
                  @change="getSelectBrandRow(scope.row)"
                >
&nbsp;
                </el-radio>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            v-if="!isSingle"
            type="selection"
            width="50"
          />
          <el-table-column
            prop="name"
            :label="$t('product.brandName')"
          >
            <template #default="scope">
              <div class="table-cell-text">
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="firstLetter"
            width="150px"
            :label="$t('product.branls')"
          />
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
        />
      </div>
    </div>
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="submitBrand()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>

const emit = defineEmits(['refreshSelectBrand'])
const props = defineProps({
  categoryId: {
    default: null,
    type: Number
  },
  isSingle: {
    default: false,
    type: Boolean
  },
  dataUrl: {
    default: '/admin/brand/listAvailableByCategoryAndName',
    type: String
  }
})

const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)

// 获取数据列表
const visible = ref(false)
let selectBrand = []
const singleSelectBrandId = ref(0)
const dataListLoading = ref(false)
let dataListSelections = []
const init = (selectBrandPar, selectBrandId) => {
  singleSelectBrandId.value = selectBrandId
  selectBrand = selectBrandPar
  visible.value = true
  dataListLoading.value = true
  if (selectBrand) {
    selectBrand.forEach(row => {
      dataListSelections.push(row)
      singleSelectBrandId.value = row
    })
  }
  getDataList()
}
const onSearch = () => {
  getDataList()
}

const brandTableRef = ref(null)
const dataList = ref([])
const brandName = ref(null)
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value
        },
        {
          categoryId: props.categoryId,
          brandName: brandName.value,
          status: 1
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    totalPage.value = data.total
    dataListLoading.value = false
    if (selectBrand) {
      nextTick(() => {
        selectBrand.forEach(row => {
          const index = dataList.value.findIndex((prodItem) => prodItem.brandId === row.brandId)
          singleSelectBrandId.value = row.brandId
          brandTableRef.value.toggleRowSelection(dataList.value[index])
        })
      })
    }
  })
}
// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}
// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}
// 单选商品事件
const getSelectBrandRow = (row) => {
  dataListSelections = [row]
  selectBrand = [row]
}
// 多选点击事件
const selectChangeHandle = (selection) => {
  dataList.value.forEach((tableItem) => {
    const selectedBrandIndex = selection.findIndex((selectedBrand) => {
      if (!selectedBrand) {
        return false
      }
      return selectedBrand.brandId === tableItem.brandId
    })
    const dataSelectedBrandIndex = dataListSelections.findIndex((dataSelectedBrand) => dataSelectedBrand.brandId === tableItem.brandId)
    if (selectedBrandIndex > -1 && dataSelectedBrandIndex === -1) {
      dataListSelections.push(tableItem)
    } else if (selectedBrandIndex === -1 && dataSelectedBrandIndex > -1) {
      dataListSelections.splice(dataSelectedBrandIndex, 1)
    }
  })
}
// 确定事件
const submitBrand = () => {
  const brands = []
  dataListSelections.forEach(item => {
    const brandIndex = brands.findIndex((brand) => brand.brandId === item.brandId)
    if (brandIndex === -1) {
      brands.push({ brandId: item.brandId, brandName: item.name })
    }
  })
  emit('refreshSelectBrand', brands)
  dataListSelections = []
  visible.value = false
}

defineExpose({
  init
})

</script>
<style lang="scss" scoped>
.component-brand-select {
  & :deep(.el-dialog__body) {
    padding-top: 20px;
    padding-bottom: 20px;
  }
  .main-container {
    margin: 0;
    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
